/*
 * @lc app=leetcode.cn id=541 lang=typescript
 *
 * [541] 反转字符串 II
 */

// @lc code=start
function reverseStr(s: string, k: number): string {
  const strs = s.split('');
  const m = strs.length;
  // 反转区间内的字符串
  const reverse = (idx: number) => {
    let l = idx;
    let r = Math.min(idx + k - 1, m - 1);
    while (l < r) {
      [strs[l], strs[r]] = [strs[r], strs[l]];
      l++, r--;
    }
  };
  // 分割出需要反转的区间
  for (let i = 0; i < m; i += 2 * k) {
    reverse(i);
  }

  return strs.join('');
}
// @lc code=end
